package cn.caijiapeng.spt.service;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;

import cn.caijiapeng.spt.bean.Operate;
import cn.caijiapeng.spt.kit.MyKit;
import cn.caijiapeng.spt.model.SysAccess;
import cn.caijiapeng.spt.model.SysUser;

public class SysAccessService {
	public final static SysAccessService srv = new SysAccessService();
	private final SysAccess dao = new SysAccess();

	public Operate<SysAccess> login(String username, String password, String ip, String userAgent) {
		SysUser user = SysUserService.srv.findByUsername(username);
		if(user == null) {
			return Operate.fail();
		}
		if(!user.getStr("password").equals(MyKit.encodeSysUserPassword(password, user.getStr("password_salt")))) {
			return Operate.fail();
		}
		//登录成功
		//保存token
		Operate<SysAccess> access = create(user.getInt("id"), username);
		//保存登录信息
		if(access.isOk()) {
			SysLoginLogService.srv.create(access.get(), ip, userAgent);
		}
		return access;
	}
	
	public void logout(String token) {
		deleteByToken(token);		
	}
	
	
	public Operate<SysAccess> create(Integer userId, String username){
		SysAccess access = new SysAccess();
		access.set("user_id", userId);
		access.set("username", username);
		access.set("token", MyKit.getUUID());
		access.set("login_time", MyKit.getCurCreateTime());
		access.set("expires_in", 3600);
		if(access.save()) {
			return Operate.ok(access);
		}
		return Operate.fail();
	}
	
	public void deleteByToken(String token) {
		Db.query("delete from " + dao.getTableName() + " where token = ?", token);
	}
	
	
	public Operate<SysAccess> findByToken(String token){
		SysAccess sysAccess = dao.getFirst(Kv.by("token = ", token));
		if(sysAccess == null) {
			return Operate.fail();
		}
		return Operate.ok(sysAccess);
	}
	
	public boolean refreshToken(Integer id) {
		SysAccess access = new SysAccess();
		access.set("id", id);
		return access.update();
	}
}
